/**
 * Created by Jacky
 *
 * brief : 此脚本用来通过api更新ssq的开奖数据
 * @info : 当前通过开彩网的免费API调用
 *         http://f.opencai.net/[编码格式]/[彩票代码]-[返回行数].[返回格式]
 *         http://f.opencai.net/utf8/ssq-10.json
 */


var fs = require('fs'),
    http = require('http');

var myReq = require('../utility/request');


var getNewData = function(row, callback){
    row = row || 5;
    var url = 'http://f.opencai.net/utf8/ssq-'+row.toString()+'.json';

    myReq.get(url, function(data){
        var json = JSON.parse(data).data;
        var rs = [];
        for(var i= 0,len=json.length; i<len; i++){
            var tmp = {
                id : json[i]['expect'],
                time : json[i].opentimestamp
            };
            var oc = json[i].opencode;
            tmp.hong = oc.substring(0, oc.indexOf('+')).split(',');
            tmp.lan = oc.substring(oc.indexOf('+')+1, oc.length);

            rs.push(tmp);
        }

        callback(rs);
    }, function(error){

    });
};


var freshData = function(callback){
    var fileName = __dirname+'/../data/ssq_'+new Date().getFullYear()+'.json';
    var d = fs.readFileSync(fileName, {
        encoding : 'utf8',
        flag : 'r'
    });
    //console.log(d);
    try{
        d = JSON.parse(d);
    }catch(e){
        d = [];
    }



    getNewData(5, function(data){
        var rs = [];
        var sid = d[0] ? d[0].id : '2015000';
        for(var i= 0,len=data.length; i<len; i++){
            if(data[i].id > sid){
                rs.push(data[i]);
            }
            else{
                break;
            }
        }

        rs = rs.concat(d);

        var str = JSON.stringify(rs);

        //write to file
        fs.writeFileSync(fileName, str, {
            encoding : 'utf8',
            flag : 'w'
        });

        console.log('data is update success.');
        console.log(str);
        callback && callback(rs);
    });
};
exports.freshData = freshData;
